package com.example.service.impl;

import com.example.common.Result;
import com.example.entity.Menu;
import com.example.entity.Permission;
import com.example.mapper.MenuMapper;
import com.example.mapper.PermissionMapper;
import com.example.service.MenuPermissionInitService;
import com.example.service.MenuPermissionMappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 菜单权限初始化服务实现
 */
@Service
public class MenuPermissionInitServiceImpl implements MenuPermissionInitService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuPermissionMappingService menuPermissionMappingService;

    @Override
    public Result<String> initMenuPermissionMapping() {
        try {
            StringBuilder result = new StringBuilder();
            
            // 获取所有菜单
            List<Menu> allMenus = menuMapper.selectList(new Menu());
            // 获取所有权限
            List<Permission> allPermissions = permissionMapper.selectList(new Permission());
            
            result.append("系统中共有 ").append(allMenus.size()).append(" 个菜单，")
                  .append(allPermissions.size()).append(" 个权限\n");
            
            // 统计菜单类型
            Map<String, Integer> menuTypeCount = new HashMap<>();
            for (Menu menu : allMenus) {
                menuTypeCount.put(menu.getMenuType(), 
                    menuTypeCount.getOrDefault(menu.getMenuType(), 0) + 1);
            }
            
            result.append("菜单类型统计：");
            for (Map.Entry<String, Integer> entry : menuTypeCount.entrySet()) {
                result.append(entry.getKey()).append("(").append(entry.getValue()).append("个) ");
            }
            result.append("\n");
            
            // 统计权限类型
            Map<String, Integer> permissionTypeCount = new HashMap<>();
            for (Permission permission : allPermissions) {
                permissionTypeCount.put(permission.getPermissionType(), 
                    permissionTypeCount.getOrDefault(permission.getPermissionType(), 0) + 1);
            }
            
            result.append("权限类型统计：");
            for (Map.Entry<String, Integer> entry : permissionTypeCount.entrySet()) {
                result.append(entry.getKey()).append("(").append(entry.getValue()).append("个) ");
            }
            result.append("\n");
            
            result.append("菜单权限映射关系已建立");
            
            return Result.success(result.toString());
        } catch (Exception e) {
            return Result.error("初始化菜单权限映射失败：" + e.getMessage());
        }
    }

    @Override
    public Result<String> checkMenuPermissionMapping() {
        try {
            StringBuilder result = new StringBuilder();
            int mappedMenuCount = 0;
            int unmappedMenuCount = 0;
            
            // 获取所有菜单
            List<Menu> allMenus = menuMapper.selectList(new Menu());
            
            for (Menu menu : allMenus) {
                // 检查每个菜单是否有对应的权限
                Set<String> permissionCodes = menuPermissionMappingService.getPermissionCodesByMenuCodes(
                    List.of(menu.getMenuCode())
                );
                
                if (permissionCodes.isEmpty()) {
                    unmappedMenuCount++;
                    result.append("未映射菜单：").append(menu.getMenuName())
                          .append("(").append(menu.getMenuCode()).append(")\n");
                } else {
                    mappedMenuCount++;
                }
            }
            
            result.insert(0, "菜单权限映射检查结果：\n")
                  .insert(0, "已映射菜单：" + mappedMenuCount + " 个\n")
                  .insert(0, "未映射菜单：" + unmappedMenuCount + " 个\n");
            
            return Result.success(result.toString());
        } catch (Exception e) {
            return Result.error("检查菜单权限映射失败：" + e.getMessage());
        }
    }

    @Override
    public Result<String> fixMenuPermissionMapping() {
        try {
            StringBuilder result = new StringBuilder();
            
            // 获取所有菜单
            List<Menu> allMenus = menuMapper.selectList(new Menu());
            // 获取所有权限
            List<Permission> allPermissions = permissionMapper.selectList(new Permission());
            
            // 创建权限编码到权限对象的映射
            Map<String, Permission> permissionCodeMap = new HashMap<>();
            for (Permission permission : allPermissions) {
                if (permission.getPermissionCode() != null) {
                    permissionCodeMap.put(permission.getPermissionCode(), permission);
                }
            }
            
            int fixedCount = 0;
            
            for (Menu menu : allMenus) {
                // 为每个菜单检查并创建对应的权限
                String menuCode = menu.getMenuCode();
                if (menuCode != null) {
                    // 根据菜单编码生成对应的权限编码
                    Set<String> expectedPermissionCodes = generatePermissionCodesForMenu(menu);
                    
                    for (String permissionCode : expectedPermissionCodes) {
                        if (!permissionCodeMap.containsKey(permissionCode)) {
                            // 创建缺失的权限
                            Permission newPermission = createPermissionForMenu(menu, permissionCode);
                            if (newPermission != null) {
                                try {
                                    permissionMapper.insert(newPermission);
                                    permissionCodeMap.put(permissionCode, newPermission);
                                    fixedCount++;
                                    result.append("为菜单 ").append(menu.getMenuName())
                                          .append(" 创建权限：").append(permissionCode).append("\n");
                                } catch (Exception e) {
                                    // 权限可能已存在，忽略错误
                                }
                            }
                        }
                    }
                }
            }
            
            result.insert(0, "修复菜单权限映射完成，共创建 " + fixedCount + " 个权限\n");
            
            return Result.success(result.toString());
        } catch (Exception e) {
            return Result.error("修复菜单权限映射失败：" + e.getMessage());
        }
    }

    /**
     * 根据菜单生成对应的权限编码
     */
    private Set<String> generatePermissionCodesForMenu(Menu menu) {
        return menuPermissionMappingService.getPermissionCodesByMenuCodes(
            List.of(menu.getMenuCode())
        );
    }

    /**
     * 为菜单创建对应的权限
     */
    private Permission createPermissionForMenu(Menu menu, String permissionCode) {
        Permission permission = new Permission();
        permission.setPermissionCode(permissionCode);
        
        // 根据权限编码生成权限名称和描述
        String permissionName = generatePermissionName(menu, permissionCode);
        String description = generatePermissionDescription(menu, permissionCode);
        
        permission.setPermissionName(permissionName);
        permission.setDescription(description);
        permission.setPermissionType("OPERATION");
        permission.setStatus(1);
        permission.setSort(0);
        permission.setParentId(0L);
        permission.setDeleted(0);
        
        return permission;
    }

    /**
     * 生成权限名称
     */
    private String generatePermissionName(Menu menu, String permissionCode) {
        String[] parts = permissionCode.split(":");
        if (parts.length >= 3) {
            String action = parts[2];
            switch (action) {
                case "view": return menu.getMenuName() + "-查看";
                case "list": return menu.getMenuName() + "-列表";
                case "add": return menu.getMenuName() + "-新增";
                case "edit": return menu.getMenuName() + "-编辑";
                case "update": return menu.getMenuName() + "-更新";
                case "delete": return menu.getMenuName() + "-删除";
                case "assign": return menu.getMenuName() + "-分配";
                case "manage": return menu.getMenuName() + "-管理";
                default: return menu.getMenuName() + "-" + action;
            }
        }
        return menu.getMenuName() + "-操作";
    }

    /**
     * 生成权限描述
     */
    private String generatePermissionDescription(Menu menu, String permissionCode) {
        return "菜单【" + menu.getMenuName() + "】对应的权限：" + permissionCode;
    }
} 